#include "sitedialog.h"
#include "ui_sitedialog.h"

SiteDialog::SiteDialog(QWidget *parent) :
    BaseEditorDialog(parent),
    ui(new Ui::SiteDialog)
{
    ui->setupUi(this);

    table=TD_SITE;

    model=new QSqlTableModel(this);
    ui->tableView->setModel(model);

    createMenu();
}

SiteDialog::~SiteDialog()
{
    delete ui;
}

void SiteDialog::updateView()
{
    model->setTable(table);
    model->setFilter(QString("article_id = %1")
                     .arg(article_id));
    model->select();

    ui->tableView->hideColumn(0);
    ui->tableView->hideColumn(1);
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("标签"));
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("网址"));
}

void SiteDialog::setId(int id)
{
    article_id=id;
    updateView();
}

void SiteDialog::on_btn_paste_label_clicked()
{
    auto label=qApp->clipboard()->text().trimmed();
    if(label.isEmpty())
        return;

    ui->label->setText(label);
}


void SiteDialog::on_btn_paste_url_clicked()
{
    auto url=qApp->clipboard()->text().trimmed();
    if(url.isEmpty())
        return;

    ui->url->setText(url);
}


bool SiteDialog::addItem(const Site &item)
{
    if(item.article_id == 0)
        return false;

    QSqlQuery query;
    auto sql=QString("insert into %1 (article_id,label,url) values (?,?,?)")
            .arg(table);
    query.prepare(sql);
    query.addBindValue(item.article_id);
    query.addBindValue(item.label);
    query.addBindValue(item.url);
    return query.exec();
}

void SiteDialog::on_btn_submit_clicked()
{
    Site item;
    item.article_id=article_id;
    item.label=ui->label->text().trimmed();
    item.url=ui->url->text().trimmed();

    if(addItem(item))
    {
        ui->label->clear();
        ui->url->clear();
        updateView();
    }
}

